// components/allOrders/index.js
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
import {
  serializeParams,
  matchDictList
} from "../../utils/index.js";
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    feedList: [],
    value1: '1',
    value2: '1',
    option1: [{
        text: "订单（全部）",
        value: "1"
      },
      {
        text: "订单（已完成）",
        value: "2"
      },
      {
        text: "订单（未完成）",
        value: "3"
      },
    ],
    option2: [{
        text: "下单时间（升序）",
        value: "1"
      },
      {
        text: "下单时间（降序）",
        value: "2"
      }
    ],
    list: [],
    refresherTriggered: false,
    queryParams: {
      pageSize: 10,
      pageNum: 1
    },
    loading: false,
    total: 0,
    totalPage: 0
  },

  /**
   * 组件的方法列表
   */
  methods: {
    async initComponent() {
      if (this.data.feedList.length == 0) {
        this.setData({
          dicts: getApp().globalData.dicts.lockType || wx.getStorageSync('dicts')["lockType"] || []
        });
        Toast.loading({
          message: '加载中...',
          forbidClick: true,
          loadingType: 'spinner',
          mask: true
        });
        this.setData({
          ['queryParams.pageNum']: 1
        })
        const {
          result: res
        } = await this.getList();
        this.setData({
          // list: res.data,
          feedList: [res.data],
          total: res.total,
          totalPage: res.totalPage
        });
        Toast.clear();
      }
    },
    async change1(e) {
      this.setData({
        value1: e.detail
      });
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner',
        mask: true
      });
      this.setData({
        ['queryParams.pageNum']: 1
      })
      const {
        result: res
      } = await this.getList();
      this.setData({
        // list: res.data,
        feedList: [res.data],
        total: res.total,
        totalPage: res.totalPage
      });
      Toast.clear();
    },
    async change2(e) {
      this.setData({
        value2: e.detail
      });
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner',
        mask: true
      });
      this.setData({
        ['queryParams.pageNum']: 1
      })
      const {
        result: res
      } = await this.getList();
      this.setData({
        // list: res.data,
        feedList: [res.data],
        total: res.total,
        totalPage: res.totalPage
      });
      Toast.clear();
    },
    successOrder(e) {
      Dialog.confirm({
          title: '提示',
          message: '是否完成该订单',
          // theme: 'round-button',
        })
        .then(async () => {
          // on confirm
          try {
            Toast.loading({
              message: '正在完场该订单',
              forbidClick: true,
              loadingType: 'spinner',
              mask: true
            });
            const res = await getApp().globalData.wxCloudRequest({
              type: "successOrder",
              openId: wx.getStorageSync("idInfo")['openid'],
              id: e.target.dataset.id
            });
            const feedList = this.data.feedList;
            for (let i = 0; i < feedList.length; i++) {
              for (let j = 0; j < feedList[i].length; j++) {
                if (feedList[i][j]['_id'] == e.target.dataset.id) {
                  this.setData({
                    [`feedList[${i}][${j}].success`]: '1'
                  });
                }
              }
            }
            Toast.clear();
            this.triggerEvent("allOrdersSuccess", {
              id: e.target.dataset.id
            })
          } catch (error) {

          }
        })
        .catch(() => {
          // on cancel
        });
    },
    showImg(e) {
      const {
        item: imgList
      } = e.target.dataset;
      wx.previewImage({
        urls: imgList.map((item) => item.filePath)
      })
    },
    setOrdersSuccess({
      id
    }) {
      const feedList = this.data.feedList;
      for (let i = 0; i < feedList.length; i++) {
        for (let j = 0; j < feedList[i].length; j++) {
          if (feedList[i][j]['_id'] == id) {
            this.setData({
              [`feedList[${i}][${j}].success`]: '1'
            });
          }
        }
      }
    },
    async bindscrolltolower() {
      if (this.data.queryParams.pageNum >= this.data.totalPage || this.data.isLoadMore) {
        return
      }
      this.setData({
        ['queryParams.pageNum']: this.data.queryParams.pageNum + 1,
        isLoadMore: true
      });
      const {
        result: res
      } = await this.getList();
      this.setData({
        // list: this.data.list.concat(res.data),
        [`feedList[${this.data.queryParams.pageNum-1}]`]: res.data,
        total: res.total,
        totalPage: res.totalPage,
        isLoadMore: false
      });
    },
    getList() {
      const {
        openid
      } = wx.getStorageSync("idInfo");
      return new Promise((resolve, reject) => {
        getApp().globalData.wxCloudRequest({
          type: "getAllOrderList",
          openId: openid,
          ...this.data.queryParams,
          success: this.data.value1,
          sortCreateTime: this.data.value2 == "1" ? "desc" : "asc"
        }).then((res) => {
          const r = {
            ...res,
            result: {
              ...res.result,
              data: res.result.data.map((item) => {
                return {
                  ...item,
                  customerData: {
                    ...item.customerData,
                    region: item.customerData.regionValue.join("") + item.customerData.address
                  },
                  sellerData: {
                    ...item.sellerData,
                    region: item.sellerData.regionValue.join("") + item.sellerData.address
                  },
                  lockInfo: {
                    ...item.lockInfo,
                    typeLabel: matchDictList(item.lockInfo.type, this.data.dicts, "dictValue", "dictLabel")
                  }
                }
              })
            }
          }
          resolve(r);
        }).catch((err) => {
          reject(err)
        })
      });
    },
    async bindrefresherrefresh(e) {
      this.setData({
        ['queryParams.pageNum']: 1,
        loading: true,
      });
      try {
        const {
          result: res
        } = await this.getList();
        this.setData({
          // list: res.data,
          total: res.total,
          feedList: [res.data],
          loading: false,
          totalPage: res.totalPage
        });
      } catch (error) {
        this.setData({
          // list: [],
          feedList: [],
          loading: false,
          total: 0,
          totalPage: 0
        });
      }
      this.setData({
        refresherTriggered: false
      })
    },
    showDetail(e) {
      const params = {
        orderId: e.target.dataset.id,
        showDetail: true
      }
      wx.navigateTo({
        url: '/pages/orderSuccess/index?' + serializeParams(params),
      })
    },
  },
})